package com.genesis.yunnanji.activity;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.support.v7.widget.Toolbar;
import android.text.TextUtils;
import android.util.Log;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.View;
import android.view.inputmethod.EditorInfo;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.bumptech.glide.Glide;
import com.bumptech.glide.request.RequestOptions;
import com.genesis.yunnanji.R;
import com.genesis.yunnanji.config.GenesisApiConfig;
import com.genesis.yunnanji.fragment.PasswordLogin;
import com.jph.takephoto.app.TakePhoto;
import com.jph.takephoto.model.InvokeParam;
import com.lidroid.xutils.BitmapUtils;
import com.lidroid.xutils.bitmap.BitmapDisplayConfig;
import com.luck.picture.lib.PictureSelector;
import com.luck.picture.lib.config.PictureConfig;
import com.luck.picture.lib.config.PictureMimeType;
import com.luck.picture.lib.entity.LocalMedia;
import com.timmy.tdialog.TDialog;
import com.timmy.tdialog.base.BindViewHolder;
import com.timmy.tdialog.listener.OnBindViewListener;
import com.timmy.tdialog.listener.OnViewClickListener;
import com.zhy.http.okhttp.OkHttpUtils;
import com.zhy.http.okhttp.callback.StringCallback;

import org.json.JSONException;
import org.json.JSONObject;
import org.xutils.common.Callback;
import org.xutils.http.RequestParams;
import org.xutils.view.annotation.Event;
import org.xutils.view.annotation.ViewInject;
import org.xutils.x;

import java.io.File;
import java.util.List;

import de.hdodenhof.circleimageview.CircleImageView;
import es.dmoral.toasty.Toasty;
import okhttp3.Call;
import top.zibin.luban.Luban;
import top.zibin.luban.OnCompressListener;

/**
 * 个人信息
 * Created by Administrator on 2017/11/3.
 */

public class MyInfo extends BaseActivity {
    @ViewInject(R.id.tb_myinfo_toolbar)
    private Toolbar mToolbar;
    @ViewInject(R.id.rl_myinfo_headicon)
    private RelativeLayout rlHeadIcon;
    @ViewInject(R.id.ll_nyinfo_nickname)
    private RelativeLayout rlNickName;
    @ViewInject(R.id.ll_nyinfo_username)
    private RelativeLayout rlUserName;
    @ViewInject(R.id.ll_nyinfo_sex)
    private RelativeLayout rlSex;
    @ViewInject(R.id.civ_myinfo_headicon)
    private CircleImageView civHeadIcon;
    @ViewInject(R.id.et_myinfo_username)
    private EditText etUserName;
    @ViewInject(R.id.et_myinfo_nickname)
    private EditText etNickName;
    @ViewInject(R.id.tv_myinfo_sex)
    private TextView tv_Sex;
    @ViewInject(R.id.tv_myinfo_save)
    private TextView save;

    private static final String TAG = MyInfo.class.getName();
    private TakePhoto takePhoto;
    private InvokeParam invokeParam;
    private Uri imageUri;
    private PopupWindow pw_chooseImage;
    private PopupWindow pw_chooseSex;
    private Button btn_photo;
    private Button btn_album;
    private Button btn_cancel;
    private TextView tv_man;
    private TextView tv_woman;
    private TextView tv_sex_cancel;
    private BitmapUtils bitmapUtils;
    BitmapDisplayConfig displayConfig;
    private int sexcode = 0;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState, R.layout.activity_myinfo);
//        getTakePhoto().onCreate(savedInstanceState);
    }

    @Override
    protected void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
//        getTakePhoto().onSaveInstanceState(outState);

    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
//        getTakePhoto().onActivityResult(requestCode, resultCode, data);
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            switch (requestCode) {
                case 10001:
                    List<LocalMedia> selectList = PictureSelector.obtainMultipleResult(data);
                    if (selectList == null || selectList.size() == 0) {
                        return;
                    }
                    String path = selectList.get(0).getCompressPath();
                    Glide.with(this).load(path).into(civHeadIcon);
                    Log.e("LK", path + "");
                    Luban.with(this).load(path).setCompressListener(new OnCompressListener() {
                        @Override
                        public void onStart() {
                        }

                        @Override
                        public void onSuccess(File file) {
                            uploadHeadIcon(file);
                        }

                        @Override
                        public void onError(Throwable e) {
                        }
                    }).launch();
                    break;
            }
        }
    }

    @Override
    protected void initView(Bundle savedInstanceState) {
        bitmapUtils = new BitmapUtils(context);
        displayConfig = new BitmapDisplayConfig();
        displayConfig.setLoadFailedDrawable(getResources().getDrawable(R.mipmap.defaultavatar));
        mToolbar.setTitle("");
        setSupportActionBar(mToolbar);
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);
        mToolbar.setNavigationOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
        etNickName.setImeOptions(EditorInfo.IME_ACTION_DONE);
        etUserName.setImeOptions(EditorInfo.IME_ACTION_DONE);
        etUserName.setText(genesisUtils.getUserProfile().getResult().getInfo().getUsername());
        etNickName.setText(genesisUtils.getUserProfile().getResult().getInfo().getNickname());
        sexcode = Integer.parseInt(genesisUtils.getUserProfile().getResult().getInfo().getSex());
        if (genesisUtils.getUserProfile().getResult().getInfo().getSex().equals("1")) {
            tv_Sex.setText("男");
        } else if (genesisUtils.getUserProfile().getResult().getInfo().getSex().equals("2")) {
            tv_Sex.setText("女");
        }
        bitmapUtils.display(civHeadIcon, GenesisApiConfig.PIC_HOST + genesisUtils.getUserImage(), displayConfig);


    }


    @Override
    protected void setUpView() {
        File file = new File(Environment.getExternalStorageDirectory(), "/yunnanji/" + System.currentTimeMillis() + ".jpg");
        if (!file.getParentFile().exists()) file.getParentFile().mkdirs();
        imageUri = Uri.fromFile(file);
        etNickName.setOnEditorActionListener(new TextView.OnEditorActionListener() {
            @Override
            public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
                if (actionId == EditorInfo.IME_ACTION_DONE || actionId == KeyEvent.ACTION_DOWN) {
                    Toast.makeText(context, etNickName.getText(), Toast.LENGTH_SHORT).show();
                    etNickName.clearFocus();
                    InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
                    imm.toggleSoftInput(0, InputMethodManager.HIDE_NOT_ALWAYS);
                    return true;
                }
                return false;
            }
        });
        etUserName.setOnEditorActionListener(new TextView.OnEditorActionListener() {
            @Override
            public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
                if (actionId == EditorInfo.IME_ACTION_DONE || actionId == KeyEvent.ACTION_DOWN) {
                    Toast.makeText(context, etUserName.getText(), Toast.LENGTH_SHORT).show();
                    etUserName.clearFocus();
                    InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
                    imm.toggleSoftInput(0, InputMethodManager.HIDE_NOT_ALWAYS);
                    return true;
                }
                return false;
            }
        });

    }

    @Event(value = {R.id.rl_myinfo_headicon, R.id.ll_nyinfo_nickname, R.id.ll_nyinfo_username, R.id.ll_nyinfo_sex, R.id.tv_myinfo_save}, type = View.OnClickListener.class)
    private void click(View v) {
        switch (v.getId()) {
            case R.id.rl_myinfo_headicon:
//                showPw();
                initAvatar();
                break;
            case R.id.ll_nyinfo_sex:
                showSex();
                break;
            case R.id.tv_myinfo_save:
                if (!TextUtils.isEmpty(etNickName.getText().toString()) && !TextUtils.isEmpty(genesisUtils.getUserImage())) {
                    saveInfo();
                } else {
                    Toast.makeText(context, "请补充资料", Toast.LENGTH_SHORT).show();
                }
                break;
        }
    }

    @SuppressLint("InflateParams")
    private void showPw() {
        new TDialog.Builder(getSupportFragmentManager())
                .setLayoutRes(R.layout.layout_pw_chooseimage)    //设置弹窗展示的xml布局
//                .setDialogView(view)  //设置弹窗布局,直接传入View
//                .setWidth(LayoutParams.MATCH_PARENT)  //设置弹窗宽度(px)
//                .setHeight(LayoutParams.WRAP_CONTENT)  //设置弹窗高度(px)
                .setScreenWidthAspect(this, 1f)   //设置弹窗宽度(参数aspect为屏幕宽度比例 0 - 1f)
                .setScreenHeightAspect(this, 0f)  //设置弹窗高度(参数aspect为屏幕宽度比例 0 - 1f)
                .setGravity(Gravity.BOTTOM)     //设置弹窗展示位置
                .setDimAmount(0.6f)     //设置弹窗背景透明度(0-1f)
                .setCancelableOutside(true)     //弹窗在界面外是否可以点击取消
                .setDialogAnimationRes(android.R.style.Animation_InputMethod)  //设置弹窗动画
                .setOnDismissListener(new DialogInterface.OnDismissListener() { //弹窗隐藏时回调方法
                    @Override
                    public void onDismiss(DialogInterface dialog) {
                        dialog.dismiss();
                    }
                })
                .addOnClickListener(R.id.btn_photo, R.id.btn_album, R.id.btn_cancel)
                .setOnViewClickListener(new OnViewClickListener() {     //View控件点击事件回调
                    @Override
                    public void onViewClick(BindViewHolder viewHolder, View view, TDialog tDialog) {
                        switch (view.getId()) {
                            case R.id.btn_photo:
//                                takePhoto.onPickFromCaptureWithCrop(imageUri, cropOptions);
                                break;
                            case R.id.btn_album:
                                initAvatar();
//                                takePhoto.onPickFromGalleryWithCrop(imageUri, cropOptions);
                                break;
                            case R.id.btn_cancel:
                                tDialog.dismiss();
                                break;
                        }
                        tDialog.dismiss();
                    }
                })
                .create()   //创建TDialog
                .show();    //展示
    }

    @SuppressLint("InflateParams")
    private void showSex() {
        new TDialog.Builder(getSupportFragmentManager())
                .setLayoutRes(R.layout.layout_myinfo_sexpick)    //设置弹窗展示的xml布局
//                .setDialogView(view)  //设置弹窗布局,直接传入View
//                .setWidth(LayoutParams.MATCH_PARENT)  //设置弹窗宽度(px)
//                .setHeight(LayoutParams.WRAP_CONTENT)  //设置弹窗高度(px)
                .setScreenWidthAspect(this, 1f)   //设置弹窗宽度(参数aspect为屏幕宽度比例 0 - 1f)
                .setScreenHeightAspect(this, 0f)  //设置弹窗高度(参数aspect为屏幕宽度比例 0 - 1f)
                .setGravity(Gravity.BOTTOM)     //设置弹窗展示位置
                .setDimAmount(0.6f)     //设置弹窗背景透明度(0-1f)
                .setCancelableOutside(true)     //弹窗在界面外是否可以点击取消
                .setDialogAnimationRes(android.R.style.Animation_InputMethod)  //设置弹窗动画
                .setOnDismissListener(new DialogInterface.OnDismissListener() { //弹窗隐藏时回调方法
                    @Override
                    public void onDismiss(DialogInterface dialog) {
                    }
                })
                .setOnBindViewListener(new OnBindViewListener() {   //通过BindViewHolder拿到控件对象,进行修改
                    @Override
                    public void bindView(BindViewHolder bindViewHolder) {
                    }
                })
                .addOnClickListener(R.id.tv_layout_man, R.id.tv_layout_woman, R.id.tv_layout_cancel)
                .setOnViewClickListener(new OnViewClickListener() {     //View控件点击事件回调
                    @Override
                    public void onViewClick(BindViewHolder viewHolder, View view, TDialog tDialog) {
                        switch (view.getId()) {
                            case R.id.tv_layout_man:
                                tv_Sex.setText("男");
                                sexcode = 1;
                                break;
                            case R.id.tv_layout_woman:
                                tv_Sex.setText("女");
                                sexcode = 2;
                                break;
                            case R.id.tv_layout_cancel:
                                tDialog.dismiss();
                                break;
                        }
                        tDialog.dismiss();
                    }
                })
                .create()   //创建TDialog
                .show();    //展示
    }

    private void uploadHeadIcon(File file) {
        RequestParams params = new RequestParams(GenesisApiConfig.HOST + GenesisApiConfig.HEAD_ICON);
        params.addBodyParameter("__apptoken__", genesisUtils.getAppToken());
        params.addBodyParameter("image", file);
        x.http().post(params, new Callback.CommonCallback<String>() {
            @Override
            public void onSuccess(String result) {
                try {
                    JSONObject jsonObject = new JSONObject(result);
                    if (jsonObject.optInt("status") == 200) {
                        genesisUtils.setUserImage(jsonObject.getJSONObject("result").optString("imgurl"));
//                        bitmapUtils.display(civHeadIcon, GenesisApiConfig.PIC_HOST + genesisUtils.getUserImage(), displayConfig);
                        RequestOptions requestOptions = new RequestOptions()
                                .error(R.mipmap.defaultavatar);
                        Glide.with(MyInfo.this).load(GenesisApiConfig.PIC_HOST + genesisUtils.getUserImage())
                                .apply(requestOptions).into(civHeadIcon);
                        Toasty.success(MyInfo.this, "头像修改成功");
                    } else {
                        Toast.makeText(context, jsonObject.optString("message"), Toast.LENGTH_SHORT).show();
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
//                Toasty.error(MyInfo.this,"Error");
            }

            @Override
            public void onCancelled(CancelledException cex) {
//                Toasty.error(MyInfo.this,"onCancelled");
            }

            @Override
            public void onFinished() {
//                Toasty.error(MyInfo.this,"onFinished");
            }
        });
    }

    private void saveInfo() {
        OkHttpUtils.post().url(GenesisApiConfig.HOST + GenesisApiConfig.SAVEINFO)
                .addParams("__apptoken__", genesisUtils.getAppToken())
                .addParams("nickname", etNickName.getText().toString())
                .addParams("sex", sexcode + "")
                .addParams("photo", genesisUtils.getUserImage())
                .build()
                .execute(new StringCallback() {
                    @Override
                    public void onError(Call call, Exception e, int id) {

                    }

                    @Override
                    public void onResponse(String response, int id) {
                        try {
                            JSONObject jsonObject = new JSONObject(response);
                            if (jsonObject.optInt("status") == 200) {
                                Toasty.success(context, jsonObject.optString("message"), Toast.LENGTH_SHORT).show();
                                Intent intent = new Intent();
                                intent.setAction(PasswordLogin.LOGIN_STATUS);
                                intent.putExtra("msg", "headicon");
                                context.sendBroadcast(intent);
                            } else {
                                Toasty.error(context, jsonObject.optString("message"), Toast.LENGTH_SHORT).show();
                            }
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    }
                });
    }

    private void initAvatar() {
        PictureSelector.create(this)
                .openGallery(PictureMimeType.ofImage())//全部.PictureMimeType.ofAll()、图片.ofImage()、视频.ofVideo()、音频.ofAudio()
//                .theme(R.style.style_picture_white)//主题样式(不设置为默认样式) 也可参考demo values/styles下 例如：R.style.picture.white.style
                .maxSelectNum(1)// 最大图片选择数量 int
                .minSelectNum(0)// 最小选择数量 int
                .imageSpanCount(4)// 每行显示个数 int
                .selectionMode(PictureConfig.SINGLE)// 多选 or 单选 PictureConfig.MULTIPLE or PictureConfig.SINGLE
                .previewImage(true)// 是否可预览图片 true or false
                .previewVideo(false)// 是否可预览视频 true or false
                .enablePreviewAudio(false) // 是否可播放音频 true or false
                .isCamera(true)// 是否显示拍照按钮 true or false
                .imageFormat(PictureMimeType.PNG)// 拍照保存图片格式后缀,默认jpeg
                .isZoomAnim(true)// 图片列表点击 缩放效果 默认true
                .sizeMultiplier(0.5f)// glide 加载图片大小 0~1之间 如设置 .glideOverride()无效
//                .setOutputCameraPath(FileUtils.getAppDefPath(FileUtils.PATH_IMAGE))// 自定义拍照保存路径,可不填
                .enableCrop(true)// 是否裁剪 true or false
                .compress(true)// 是否压缩 true or false
                // .glideOverride()// int glide 加载宽高，越小图片列表越流畅，但会影响列表图片浏览的清晰度
                .withAspectRatio(1, 1)// int 裁剪比例 如16:9 3:2 3:4 1:1 可自定义
                // .hideBottomControls()// 是否显示uCrop工具栏，默认不显示 true or false
                // .isGif()// 是否显示gif图片 true or false
//                .compressSavePath(FileUtils.getAppDefPath(FileUtils.PATH_IMAGE))//压缩图片保存地址
                .freeStyleCropEnabled(false)// 裁剪框是否可拖拽 true or false
                .circleDimmedLayer(false)// 是否圆形裁剪 true or false
                .showCropFrame(true)// 是否显示裁剪矩形边框 圆形裁剪时建议设为false   true or false
                .showCropGrid(true)// 是否显示裁剪矩形网格 圆形裁剪时建议设为false    true or false
                .openClickSound(false)// 是否开启点击声音 true or false
                // .selectionMedia()// 是否传入已选图片 List<LocalMedia> list
                // .previewEggs()// 预览图片时 是否增强左右滑动图片体验(图片滑动一半即可看到上一张是否选中) true or false
                // .cropCompressQuality()// 裁剪压缩质量 默认90 int
                .minimumCompressSize(100)// 小于100kb的图片不压缩
                .synOrAsy(true)//同步true或异步false 压缩 默认同步
                // .cropWH()// 裁剪宽高比，设置如果大于图片本身宽高则无效 int
                .rotateEnabled(true) // 裁剪是否可旋转图片 true or false
                .scaleEnabled(true)// 裁剪是否可放大缩小图片 true or false
                // .videoQuality()// 视频录制质量 0 or 1 int
                //  .videoMaxSecond(15)// 显示多少秒以内的视频or音频也可适用 int
                // .videoMinSecond(10)// 显示多少秒以内的视频or音频也可适用 int
                // .recordVideoSecond()//视频秒数录制 默认60s int
                .forResult(10001);//结果回调onActivityResult code
    }

}
